package com.tarena.lbs.common.exception;

import com.tarena.lbs.common.response.JsonResult;
import com.tarena.lbs.common.response.StatusCode;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理 ServiceException 异常
     */
    @ExceptionHandler(ServiceException.class)
    public JsonResult<Void> handleServiceException(ServiceException e) {
        // 确保 code 不为 null
        StatusCode statusCode = (e.getStatusCode() != null) ? e.getStatusCode() : StatusCode.SYSTEM_ERROR;
        Integer code = statusCode.getCode();
        String message = (e.getMessage() != null) ? e.getMessage() : "业务异常";

        log.warn("业务异常，code: {}, message: {}", code, message);
        return JsonResult.error(code, message);
    }

    /**
     * 处理参数校验异常 - @Validated 在方法参数上
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public JsonResult<Void> handleConstraintViolationException(ConstraintViolationException e) {
        String message = e.getConstraintViolations().stream()
                .map(violation -> violation.getPropertyPath() + ": " + violation.getMessage())
                .findFirst()
                .orElse("参数校验失败");

        log.warn("参数校验异常: {}", message);
        return JsonResult.error(StatusCode.VALIDATE_ERROR.getCode(), message);
    }

    /**
     * 处理参数校验异常 - @Valid 在对象上
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getFieldErrors().stream()
                .map(error -> error.getField() + ": " + error.getDefaultMessage())
                .findFirst()
                .orElse("参数校验失败");

        log.warn("参数校验异常: {}", message);
        return JsonResult.error(StatusCode.VALIDATE_ERROR.getCode(), message);
    }

    /**
     * 处理参数绑定异常
     */
    @ExceptionHandler(BindException.class)
    public JsonResult<Void> handleBindException(BindException e) {
        String message = e.getFieldErrors().stream()
                .map(error -> error.getField() + ": " + error.getDefaultMessage())
                .findFirst()
                .orElse("参数绑定失败");

        log.warn("参数绑定异常: {}", message);
        return JsonResult.error(StatusCode.VALIDATE_ERROR.getCode(), message);
    }

    /**
     * 处理 JSON 解析异常
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public JsonResult<Void> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.warn("JSON解析异常: {}", e.getMessage());
        return JsonResult.error(StatusCode.VALIDATE_ERROR.getCode(), "请求参数格式错误");
    }

    /**
     * 处理 IllegalArgumentException 异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public JsonResult<Void> handleIllegalArgumentException(IllegalArgumentException e) {
        log.warn("参数异常: {}", e.getMessage());
        return JsonResult.error(StatusCode.VALIDATE_ERROR.getCode(), e.getMessage());
    }

    /**
     * 处理所有其他异常
     */
    @ExceptionHandler(Exception.class)
    public JsonResult<Void> handleException(Exception e) {
        log.error("系统异常: ", e);
        return JsonResult.error(StatusCode.SYSTEM_ERROR.getCode(), "系统异常，请联系管理员");
    }
}